<?php
declare(strict_types=1);
namespace app\admin\service;

use app\admin\model\ArcModel;
use app\admin\model\ArcModelField;
use app\admin\service\interface\ModelService;
class ModelServiceImpl implements ModelService
{
    public function add(string $name, string $table){
        ArcModel::create(["name"=> $name,""=> $table]);
    }
    public function edit(int $id, string $name, string $table){
        $model = ArcModel::find($id);
        if(!$model){
            throw new \Exception("模型不存在！");
        }
        $model->name = $name;
        $model->table = $table;
        $model->save();
        
    }
    public function delete(){

    }
    public function sync_table(){

    }
    public function filed_add(int $model_id, string $field_name, string $field_type, string $data_type,string $label=""){
        $model = ArcModel::find($model_id);
        if(!$model){
            throw new \Exception("模型不存在！");
        }
        if(!in_array($field_type, ArcModelField::FIELD_TYPES) || !in_array($data_type, ArcModelField::DATA_TYPES)){
            throw new \Exception("字段格式不支持！");
        }
        $field = new ArcModelField();
        $field->model_id = $model_id;
        $field->field_name = $field_name;
        $field->field_type = $field_type;
        $field->data_type = $data_type;
        $field->label = $label;
        $field->save();
    }
    public function filed_edit(int $field_id,int $model_id, string $field_name, string $field_type, string $date_type,string $label=""){
        $model = ArcModelField::find($field_id);
        if(!$model){
            throw new \Exception("模型字段不存在！");
        }
        if(!in_array($field_type, ArcModelField::FIELD_TYPES) || !in_array($date_type, ArcModelField::DATA_TYPES)){
            throw new \Exception("字段格式不支持！");
        }
        $model->field_name = $field_name;
        $model->field_type = $field_type;
        $model->date_type = $date_type;
        $model->label = $label;
        $model->save();
    }
    private function filed_save()
    {
        
    }
    public function filed_delete(int $field_id){
        $model = ArcModelField::find($field_id);
        if(!$model){
            throw new \Exception("模型字段不存在！");
        }
        $model->delete();
    }
}
